#include<iostream>
#include<string>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

//客户端一定要先访问服务器 客户端未来一定要先知道服务器的ip和 port

// ./udp_client sever_ip sever_port
// ./udp_client 127.0.0.1 8888
int main(int argc, char *argv[])
{
    if(argc != 3)//参数个数
    {
        std::cerr << "Usage: " << argv[0] << "sever_ip sever_port" << std::endl;
        exit(0);
    }

    std::string sever_ip = argv[1];
    uint16_t sever_port = std::stoi(argv[2]);

    //创建套接字
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(1);
    }
    //client 的端口号 一般不让用户自己设定 而是让client OS 随机选择
    //client 需要bind自己的ip和端口 但是client 不需要显示bind自己的 ip和端口
    //client 再首次向服务器发送数据的时候 os 会自动给 client bind ip 和端口
    
    struct sockaddr_in sever;
    memset(&sever, 0, sizeof(sever));
    sever.sin_family = AF_INET;
    sever.sin_port = htons(sever_port);
    sever.sin_addr.s_addr = inet_addr(sever_ip.c_str());

    while(1)
    {
        // !!!!! 注意client 套接字要么收要么发 没加多线程 没法全双工
        std::string line;
        std::cout << "Plase Enter#";
        std::getline(std::cin, line);
        
        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr*)&sever, sizeof(sever)); //发送消息 需要目标
        if(n > 0)
        {
            //收消息不一定是 你给发消息的sever
            struct sockaddr_in temp;
            socklen_t len = sizeof(temp);
            char buffer[1024];
            int m = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&temp, &len);
            if(m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                std:: cout << "recvfrom error" << std::endl;
                break;
            }

        }
        else
        {
            std:: cout << "sendto error" << std::endl;
            break;
        }
        

    }

    ::close(sockfd);

    return 0;
}